package controller.dao;

import model.*;

import java.util.*;

import javax.persistence.*;

public class Dao_Client {
	EntityManager manager;
	
	public boolean save(Client client) {
		try	{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(client);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public List<Client> listAll(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Client c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Client> Clients =  query.getResultList();
		manager.close();
		return Clients;
	}
	
	public List<Client> listAll(int inicio, int quant){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Client c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Client> clients =  query.setMaxResults(quant).setFirstResult(inicio).getResultList();
		manager.close();
		return clients;
	}
	
	public Long totalClients(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT count(c) FROM Client c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		manager.close();
		return total;
	}
	
	public Client logClient(String name, String pass){
		try {
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT c FROM Client c where c.login = :n and c.password = :p" );
		query.setParameter("n", name);
		query.setParameter("p", pass);
		Client client = (Client) query.getSingleResult();
		manager.close();
		if(client != null)
			return client;
		else
			return null;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	
	public boolean update(Client client){
		try{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(client);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public boolean delete(Client client){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(client);
			manager.getTransaction().commit();
			manager.close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public Client list(int id){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();	
			Client client = manager.find(Client.class, id);
			manager.close();
			return client;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
}
